<template>
    <a-spin tip="上传文件..." :spinning="loading" class="clearfix">
        <a-upload-dragger
            name="file"
            :multiple="true"
            :fileList="fileList"
            :disabled="disabled"
            :customRequest="downloadFilesCustomRequest"
            :remove="removeFile"
        >
            <p class="ant-upload-drag-icon">
                <a-icon type="inbox" />
            </p>
            <p class="ant-upload-text">点击或拖拽上传文件</p>
        </a-upload-dragger>
    </a-spin>
</template>
<script>
import { uploadFile } from '@/api/upload';

export default {
    name: 'UploadFile',
    props: {
        list: {
            type: Array,
            default: () => []
        },
        disabled: {
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
            previewImage: '',
            previewVisible: false,
            loading: false
        };
    },
    computed: {
        fileList() {
            let fileList = [];
            let list = this.list;
            if (list && list.length) {
                list.map((item, index) => {
                    let name = item.substring(item.lastIndexOf('/') + 1);
                    fileList.push({
                        uid: index,
                        status: 'done',
                        name: name,
                        url: item
                    });
                });
            }
            console.log(fileList)
            return fileList;
        }
    },
    methods: {
        // 重写a-upload的文件上传处理方式
        async downloadFilesCustomRequest(data) {
            console.log(data);
            this.loading = true;
            await this.saveFile(data);
        },
        // 上传并保存文件
        async saveFile(data) {
            try {
                const formData = new FormData();
                formData.append('file', data.file);
                let res = await uploadFile(formData);
                let { data: imgUrl } = res;
                this.$emit('upload', { imgUrl, name: data.file.name });
            } catch (err) {
                console.log(err);
            } finally {
                this.loading = false;
            }
        },
        //删除文件
        async removeFile(file) {
            let { uid } = file;
            this.$emit('delete', uid);
        },
        handleCancel() {
            this.previewVisible = false;
        },
        async handlePreview(file) {
            console.log(file);
            this.previewImage = file.url;
            this.previewVisible = true;
        }
    }
};
</script>
<style lang="scss" scoped>
::v-deep .ant-upload.ant-upload-disabled {
    display: none;
}
.tip {
    margin: 0;
    line-height: 0;
    font-size: 12px;
    color: #999;
}
</style>
